package DynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: homechen
 * Date: 2024-03-24
 * Time: 14:08
 */
// 动态代理
class MyInvocationHandler implements InvocationHandler {
    private Object target;
    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invoking method: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After invoking method: " + method.getName());
        return result; // 结果传递回去
    }
}
// 定义接口
interface Hello {
    void sayHi();
}
// 实现接口类
class HelloImpl implements Hello {

    @Override
    public void sayHi() {
        System.out.println("hello word");
    }
}
public class DynamicProxyDemo {
    public static void main(String[] args) {
        Hello hello = new HelloImpl();
        // 创建动态代理器
        MyInvocationHandler handler = new MyInvocationHandler(hello);
        Hello proxyHello = (Hello) Proxy.newProxyInstance(
                Hello.class.getClassLoader(),
                new Class[]{Hello.class},
                handler);
        proxyHello.sayHi();
    }
}
